package com.heima.user.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;


@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    ApUserMapper apUserMapper;


    @Override
    public ResponseResult login(LoginDTO dto) {
        //1.如果手机号 和 密码不为空， 用账户密码来登录
        String phone = dto.getPhone();
        String password = dto.getPassword();
        if (StringUtils.isNotBlank(phone)&&StringUtils.isNotBlank(password)){
            //1.1根据手机号查询用户
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, phone));
            if (apUser == null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
            //1.2判断输入的密码和用户密码是否一致
            String inputPwd = DigestUtils.md5DigestAsHex((password + apUser.getSalt()).getBytes());
            if (!inputPwd.equals(apUser.getPassword())){
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
            }
            // TODO:1.3检查用户的状态
            //1.4颁发token
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            //1.5返回结果：data{token:"",user:""}
            Map map = new HashMap<>();
            map.put("token",token);
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        }else {
         //2.如果手机号或密码为空，使用设备id登录
            //2.1检查设备id
            if (dto.getEquipmentId()==null){
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名密码  和 设备id  全部为空");
            }
            //2.2直接颁发token 用户id存为0
            String token = AppJwtUtil.getToken(0L);
            //2.3返回结果： data{token:""}
            Map map = new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
